<template>
  <div class="profile-page">
    <!-- 用户信息卡片 -->
    <div class="user-header">
      <div class="user-info">
        <div class="avatar-container" @click="showAvatarSelector">
          <img :src="userAvatar" :alt="username" class="user-avatar" />
        </div>
        <div class="user-details">
          <template v-if="isLoggedIn">
            <h3 class="username">{{ username }}</h3>
            <p class="user-bio">{{ userBio }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-value">{{ formatNumber(userStats.articles) }}</span>
                <span class="stat-label">文章</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ formatNumber(userStats.likes) }}</span>
                <span class="stat-label">点赞数</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ formatNumber(userStats.liked) }}</span>
                <span class="stat-label">被点赞数</span>
              </div>
            </div>
          </template>
          <template v-else>
            <h3 class="username">未登录</h3>
            <van-button type="primary" size="small" @click="showLoginPopup = true">登录 / 注册</van-button>
          </template>
        </div>
      </div>
    </div>
    
    <!-- 实用工具 -->
    <div class="tools-section">
      <div class="section-title">实用工具</div>
      <div class="tools-grid">
        <div class="tool-item" @click="navigateTo('/ai-chat')">
          <div class="tool-icon" style="background-color: #8A2BE2;">
            <van-icon name="chat" color="#fff" size="24" />
          </div>
          <span class="tool-name">AI聊天</span>
        </div>
        <div class="tool-item" @click="navigateTo('/compiler')">
          <div class="tool-icon" style="background-color: #20B2AA;">
            <van-icon name="points" color="#fff" size="24" />
          </div>
          <span class="tool-name">在线编译</span>
        </div>
        <div class="tool-item" @click="navigateTo('/article/create')">
          <div class="tool-icon" style="background-color: #FF6347;">
            <van-icon name="edit" color="#fff" size="24" />
          </div>
          <span class="tool-name">创作文章</span>
        </div>
        <div class="tool-item" @click="showThemeSettings">
          <div class="tool-icon" style="background-color: #4682B4;">
            <van-icon name="brush-o" color="#fff" size="24" />
          </div>
          <span class="tool-name">主题设置</span>
        </div>
        <div class="tool-item" @click="navigateTo('/profile/history')">
          <div class="tool-icon" style="background-color: #9370DB;">
            <van-icon name="clock-o" color="#fff" size="24" />
          </div>
          <span class="tool-name">浏览历史</span>
        </div>
      </div>
    </div>
    
    <!-- 我的功能 -->
    <div class="features-section">
      <div class="section-title">我的功能</div>
      <div class="feature-list">
        <div class="feature-item" @click="navigateTo('/profile/articles')">
          <van-icon name="notes-o" size="24" class="feature-icon" />
          <span class="feature-name">我的创作</span>
          <van-icon name="arrow" class="feature-arrow" />
        </div>
        <div class="feature-item" @click="navigateTo('/profile/likes')">
          <van-icon name="like-o" size="24" class="feature-icon" />
          <span class="feature-name">我的点赞</span>
          <van-icon name="arrow" class="feature-arrow" />
        </div>
        <div class="feature-item" @click="navigateTo('/profile/history')">
          <van-icon name="clock-o" size="24" class="feature-icon" />
          <span class="feature-name">浏览历史</span>
          <van-icon name="arrow" class="feature-arrow" />
        </div>
        <div class="feature-item" @click="showPasswordChangeDialog">
          <van-icon name="lock" size="24" class="feature-icon" />
          <span class="feature-name">修改密码</span>
          <van-icon name="arrow" class="feature-arrow" />
        </div>
      </div>
    </div>
    
    <!-- 设置与帮助 -->
    <div class="settings-section">
      <div class="section-title">设置与帮助</div>
      <div class="feature-list">
        <div class="feature-item" @click="showFeedbackDialog">
          <van-icon name="comment-o" size="24" class="feature-icon" />
          <span class="feature-name">意见反馈</span>
          <van-icon name="arrow" class="feature-arrow" />
        </div>
        <div class="feature-item" @click="showAboutDialog">
          <van-icon name="info-o" size="24" class="feature-icon" />
          <span class="feature-name">关于我们</span>
          <van-icon name="arrow" class="feature-arrow" />
        </div>
      </div>
    </div>
    
    <!-- 退出登录按钮 -->
    <div class="logout-button" v-if="isLoggedIn">
      <van-button block type="danger" @click="handleLogout">退出登录</van-button>
    </div>
    
    <!-- 登录弹窗 -->
    <van-popup
      v-model:show="showLoginPopup"
      position="bottom"
      round
      :style="{ height: '70%' }"
    >
      <div class="login-popup">
        <div class="login-header">
          <h3>登录/注册</h3>
          <van-icon name="cross" @click="showLoginPopup = false" />
        </div>
        
        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="loginForm.username"
              name="username"
              label="用户名"
              placeholder="请输入用户名"
              :rules="[{ required: true, message: '请输入用户名' }]"
            />
            <van-field
              v-model="loginForm.password"
              type="password"
              name="password"
              label="密码"
              placeholder="请输入密码"
              :rules="[{ required: true, message: '请输入密码' }]"
            />
          </van-cell-group>
          
          <div class="login-actions">
            <van-button round block type="primary" native-type="submit" :loading="loginLoading">
              登录
            </van-button>
            <div class="register-link">
              还没有账号？<span @click="switchToRegister">立即注册</span>
            </div>
          </div>
        </van-form>
      </div>
    </van-popup>
    
    <!-- 修改密码弹窗 -->
    <van-dialog
      v-model:show="showPasswordDialog"
      title="修改密码"
      show-cancel-button
      @confirm="confirmChangePassword"
    >
      <van-form>
        <van-cell-group inset>
          <van-field
            v-model="passwordForm.oldPassword"
            type="password"
            name="oldPassword"
            label="当前密码"
            placeholder="请输入当前密码"
            :rules="[{ required: true, message: '请输入当前密码' }]"
          />
          <van-field
            v-model="passwordForm.newPassword"
            type="password"
            name="newPassword"
            label="新密码"
            placeholder="请输入新密码"
            :rules="[{ required: true, message: '请输入新密码' }]"
          />
          <van-field
            v-model="passwordForm.confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入新密码"
            :rules="[{ required: true, message: '请再次输入新密码' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>
    
    <!-- 头像选择弹窗 -->
    <van-popup
      v-model:show="showAvatarPopup"
      position="bottom"
      round
      :style="{ height: '40%' }"
    >
      <div class="avatar-popup">
        <div class="popup-header">
          <h3>更换头像</h3>
          <van-icon name="cross" @click="showAvatarPopup = false" />
        </div>
        
        <div class="avatar-options">
          <div class="option-item" @click="selectAvatarFromCamera">
            <van-icon name="photograph" size="24" />
            <span>拍照</span>
          </div>
          <div class="option-item" @click="selectAvatarFromAlbum">
            <van-icon name="photo-o" size="24" />
            <span>从相册选择</span>
          </div>
        </div>
      </div>
    </van-popup>
    
    <!-- 主题设置弹窗 -->
    <van-popup
      v-model:show="showThemePopup"
      position="bottom"
      round
      :style="{ height: '70%' }"
    >
      <div class="theme-popup">
        <div class="popup-header">
          <h3>主题设置</h3>
          <van-icon name="cross" @click="showThemePopup = false" />
        </div>
        
        <div class="theme-options">
          <div class="section-subtitle">模式选择</div>
          <div class="theme-mode-options">
            <div 
              class="mode-item" 
              :class="{ active: themeMode === 'light' }"
              @click="setThemeMode('light')"
            >
              <div class="mode-icon">
                <van-icon name="sunny-o" size="24" />
              </div>
              <span>浅色模式</span>
            </div>
            <div 
              class="mode-item" 
              :class="{ active: themeMode === 'dark' }"
              @click="setThemeMode('dark')"
            >
              <div class="mode-icon">
                <van-icon name="moon-o" size="24" />
              </div>
              <span>深色模式</span>
            </div>
            <div 
              class="mode-item" 
              :class="{ active: themeMode === 'auto' }"
              @click="setThemeMode('auto')"
            >
              <div class="mode-icon">
                <van-icon name="setting-o" size="24" />
              </div>
              <span>跟随系统</span>
            </div>
          </div>
          
          <div class="section-subtitle">主题颜色</div>
          <div class="theme-color-options">
            <div 
              v-for="color in themeColors" 
              :key="color.name"
              class="color-item"
              :class="{ active: currentThemeColor === color.value }"
              :style="{ backgroundColor: color.value }"
              @click="setThemeColor(color.value)"
            ></div>
          </div>
          
          <div class="section-subtitle">背景图片</div>
          <div class="theme-image-options">
            <div 
              v-for="(image, index) in themeImages" 
              :key="index"
              class="image-item"
              :class="{ active: currentThemeImage === image }"
              :style="{ backgroundImage: `url(${image})` }"
              @click="setThemeImage(image)"
            ></div>
            <div class="image-item upload-item" @click="uploadCustomImage">
              <van-icon name="plus" size="24" />
              <span>上传图片</span>
            </div>
          </div>
        </div>
        
        <input 
          type="file" 
          ref="imageInput" 
          accept="image/*" 
          style="display: none"
          @change="handleImageUpload" 
        />
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { useUserStore } from '../../store/user'
import { formatNumber } from '../../utils/common'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const isLoggedIn = computed(() => userStore.isLoggedIn)
const username = computed(() => userStore.username)
const userAvatar = computed(() => userStore.userAvatar)
const userBio = ref('热爱技术，分享生活')
const userStats = ref({
  articles: 12,
  likes: 256,
  liked: 58
})

// 主题设置
const isDarkTheme = computed(() => userStore.preferences.theme === 'dark')
const showThemePopup = ref(false)
const themeMode = ref('light')
const currentThemeColor = ref('#1989fa')
const currentThemeImage = ref('')
const imageInput = ref(null)

// 预设主题颜色
const themeColors = [
  { name: '蓝色', value: '#1989fa' },
  { name: '绿色', value: '#07c160' },
  { name: '红色', value: '#ee0a24' },
  { name: '橙色', value: '#ff8200' },
  { name: '紫色', value: '#8a2be2' },
  { name: '青色', value: '#20b2aa' }
]

// 预设主题背景图片
const themeImages = [
  'https://picsum.photos/id/1018/300/600',
  'https://picsum.photos/id/1019/300/600',
  'https://picsum.photos/id/1021/300/600',
  'https://picsum.photos/id/1033/300/600'
]

// 登录相关
const showLoginPopup = ref(false)
const loginLoading = ref(false)
const loginForm = ref({
  username: '',
  password: ''
})

// 密码修改相关
const showPasswordDialog = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 头像选择相关
const showAvatarPopup = ref(false)

// 导航到指定页面
const navigateTo = (path) => {
  if (path.includes('/profile/') && !isLoggedIn.value) {
    showToast('请先登录')
    showLoginPopup.value = true
    return
  }
  
  // 特殊处理AI聊天页面
  if (path === '/ai-chat') {
    console.log('导航到AI聊天页面')
  }
  
  router.push(path)
}

// 切换主题
const toggleTheme = () => {
  const newTheme = userStore.preferences.theme === 'dark' ? 'light' : 'dark'
  userStore.updateTheme(newTheme)
  showToast(`已切换到${newTheme === 'dark' ? '深色' : '浅色'}主题`)
}

// 登录提交
const onSubmit = async () => {
  loginLoading.value = true
  
  try {
    const result = await userStore.login(loginForm.value)
    
    if (result.success) {
      showToast('登录成功')
      showLoginPopup.value = false
    } else {
      showToast('登录失败: ' + result.message)
    }
  } catch (error) {
    showToast('登录失败: ' + error.message)
  } finally {
    loginLoading.value = false
  }
}

// 切换到注册
const switchToRegister = () => {
  showToast('注册功能开发中')
}

// 退出登录
const handleLogout = () => {
  showDialog({
    title: '退出登录',
    message: '确定要退出登录吗？',
    showCancelButton: true
  }).then(() => {
    userStore.logout()
    showToast('已退出登录')
  }).catch(() => {
    // 取消操作
  })
}

// 显示修改密码对话框
const showPasswordChangeDialog = () => {
  if (!isLoggedIn.value) {
    showToast('请先登录')
    showLoginPopup.value = true
    return
  }
  
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  showPasswordDialog.value = true
}

// 确认修改密码
const confirmChangePassword = () => {
  if (!passwordForm.value.oldPassword) {
    showToast('请输入当前密码')
    return
  }
  
  if (!passwordForm.value.newPassword) {
    showToast('请输入新密码')
    return
  }
  
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    showToast('两次输入的密码不一致')
    return
  }
  
  // 模拟密码修改
  setTimeout(() => {
    showToast('密码修改成功')
  }, 1000)
}

// 显示头像选择器
const showAvatarSelector = () => {
  if (!isLoggedIn.value) {
    showToast('请先登录')
    showLoginPopup.value = true
    return
  }
  
  showAvatarPopup.value = true
}

// 从相机选择头像
const selectAvatarFromCamera = () => {
  showToast('拍照功能开发中')
  showAvatarPopup.value = false
}

// 从相册选择头像
const selectAvatarFromAlbum = () => {
  showToast('已选择从相册选择头像')
  // 实际项目中应该调用相册API
  setTimeout(() => {
    userStore.updateAvatar('https://picsum.photos/id/1015/200/200')
    showToast('头像更新成功')
    showAvatarPopup.value = false
  }, 1000)
}

// 显示意见反馈对话框
const showFeedbackDialog = () => {
  showDialog({
    title: '意见反馈',
    message: '感谢您的反馈！我们将不断改进产品体验。',
    confirmButtonText: '我知道了'
  })
}

// 显示关于我们对话框
const showAboutDialog = () => {
  showDialog({
    title: '关于我们',
    message: '我的Vue3应用 v1.0.0\n一个基于Vue 3、Vite和TypeScript构建的移动应用程序。',
    confirmButtonText: '我知道了'
  })
}

// 显示主题设置
const showThemeSettings = () => {
  // 初始化当前主题设置
  themeMode.value = userStore.preferences.theme || 'light'
  currentThemeColor.value = userStore.preferences.themeColor || '#1989fa'
  currentThemeImage.value = userStore.preferences.themeImage || ''
  
  showThemePopup.value = true
}

// 设置主题模式
const setThemeMode = (mode) => {
  themeMode.value = mode
  userStore.updateTheme(mode)
  applyTheme()
}

// 设置主题颜色
const setThemeColor = (color) => {
  currentThemeColor.value = color
  userStore.updateThemeColor(color)
  applyTheme()
}

// 设置主题背景图片
const setThemeImage = (image) => {
  currentThemeImage.value = image
  userStore.updateThemeImage(image)
  applyTheme()
}

// 应用主题设置
const applyTheme = () => {
  document.documentElement.style.setProperty('--primary-color', currentThemeColor.value)
  
  if (currentThemeImage.value) {
    document.body.style.backgroundImage = `url(${currentThemeImage.value})`
    document.body.style.backgroundSize = 'cover'
    document.body.style.backgroundAttachment = 'fixed'
  } else {
    document.body.style.backgroundImage = 'none'
  }
  
  showToast('主题设置已更新')
}

// 上传自定义背景图片
const uploadCustomImage = () => {
  imageInput.value.click()
}

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    const imageDataUrl = e.target.result
    setThemeImage(imageDataUrl)
  }
  reader.readAsDataURL(file)
}
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: calc(var(--tabbar-height) + 50px);
  
  .user-header {
    background-color: var(--primary-color);
    padding: 20px 16px;
    color: #fff;
    
    .user-info {
      display: flex;
      align-items: center;
      
      .avatar-container {
        margin-right: 16px;
        
        .user-avatar {
          width: 70px;
          height: 70px;
          border-radius: 50%;
          border: 2px solid rgba(255, 255, 255, 0.8);
          object-fit: cover;
        }
      }
      
      .user-details {
        flex: 1;
        
        .username {
          font-size: 20px;
          font-weight: 600;
          margin-bottom: 4px;
        }
        
        .user-bio {
          font-size: 14px;
          margin-bottom: 8px;
          opacity: 0.9;
        }
        
        .user-stats {
          display: flex;
          
          .stat-item {
            margin-right: 16px;
            display: flex;
            flex-direction: column;
            align-items: center;
            
            .stat-value {
              font-size: 16px;
              font-weight: 600;
            }
            
            .stat-label {
              font-size: 12px;
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: var(--text-color);
    padding: 16px 16px 8px;
  }
  
  .tools-section {
    margin-top: 12px;
    background-color: var(--background-color-light);
    
    .tools-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      padding: 0 16px 16px;
      
      .tool-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 12px 0;
        
        .tool-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-bottom: 8px;
        }
        
        .tool-name {
          font-size: 12px;
          color: var(--text-color);
        }
      }
    }
  }
  
  .features-section, .settings-section {
    margin-top: 12px;
    background-color: var(--background-color-light);
    
    .feature-list {
      .feature-item {
        display: flex;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid var(--border-color-light);
        
        &:last-child {
          border-bottom: none;
        }
        
        .feature-icon {
          color: var(--primary-color);
          margin-right: 12px;
        }
        
        .feature-name {
          flex: 1;
          font-size: 16px;
          color: var(--text-color);
        }
        
        .feature-arrow {
          color: var(--text-color-tertiary);
        }
      }
    }
  }
  
  .logout-button {
    margin: 24px 16px;
  }
  
  .login-popup {
    padding: 16px;
    
    .login-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      
      h3 {
        font-size: 18px;
        font-weight: 500;
      }
    }
    
    .login-actions {
      margin-top: 24px;
      
      .register-link {
        margin-top: 16px;
        text-align: center;
        font-size: 14px;
        color: var(--text-color-secondary);
        
        span {
          color: var(--primary-color);
        }
      }
    }
  }
  
  .avatar-popup {
    padding: 16px;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      
      h3 {
        font-size: 18px;
        font-weight: 500;
      }
    }
    
    .avatar-options {
      display: flex;
      justify-content: space-around;
      
      .option-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .van-icon {
          font-size: 32px;
          margin-bottom: 8px;
          color: var(--primary-color);
        }
        
        span {
          font-size: 14px;
          color: var(--text-color);
        }
      }
    }
  }
  
  .theme-popup {
    padding: 16px;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      
      h3 {
        font-size: 18px;
        font-weight: 500;
      }
    }
    
    .theme-options {
      .section-subtitle {
        font-size: 14px;
        font-weight: 500;
        color: var(--text-color);
        margin: 20px 0 12px;
      }
      
      .theme-mode-options {
        display: flex;
        justify-content: space-between;
        
        .mode-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 12px;
          background-color: var(--background-color);
          border-radius: 8px;
          width: 30%;
          
          &.active {
            background-color: var(--primary-color);
            color: #fff;
            
            .mode-icon {
              color: #fff;
            }
          }
          
          .mode-icon {
            margin-bottom: 8px;
            color: var(--primary-color);
          }
          
          span {
            font-size: 12px;
          }
        }
      }
      
      .theme-color-options {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        
        .color-item {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          position: relative;
          
          &.active::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.8);
          }
        }
      }
      
      .theme-image-options {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin-bottom: 20px;
        
        .image-item {
          width: 80px;
          height: 80px;
          border-radius: 8px;
          background-size: cover;
          background-position: center;
          position: relative;
          
          &.active {
            border: 2px solid var(--primary-color);
          }
          
          &.upload-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background-color: var(--background-color);
            border: 1px dashed var(--border-color);
            
            span {
              font-size: 12px;
              margin-top: 4px;
              color: var(--text-color-secondary);
            }
          }
        }
      }
    }
  }
}
</style>